package com.king.springcloud.controller;

import com.king.springcloud.service.PaymentHystrixService;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author king
 * @date 2020/9/10 23:02
 */
@Slf4j
@RestController
@RequestMapping("/consumer")
@DefaultProperties(defaultFallback = "paymentGlobalFallbackMethod")   // 设置默认全局 fallback
public class OrderHystrixController {

    @Resource
    private PaymentHystrixService paymentHystrixService;

    /**
     * 正常访问
     * @param id id
     * @return 结果
     */
    @GetMapping("/payment/hystrix/ok/{id}")
    public String paymentInfo_OK(@PathVariable("id") Integer id){
        return paymentHystrixService.paymentInfoOK(id);
    }

    /**
     * 异常访问
     * @param id id
     * @return 结果
     */
    @GetMapping("/payment/hystrix/timeout/{id}")
    public String paymentInfoTimeout(@PathVariable("id")Integer id){
        return paymentHystrixService.paymentInfoTimeout(id);
    }

    /**
     * 超时补救
     *  HystrixCommand
     *      fallbackMethod 出错调用补救方法
     *      commandProperties
     *          HystrixProperty 响应峰值设置, 超过则调用补救方法
     * @param id id
     * @return 结果
     */
//    @HystrixCommand(fallbackMethod = "paymentInfo_TimeoutHandler", commandProperties = {
//            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
//    })    // 自定义补救策略
    @HystrixCommand // 开启服务降级, 未指定的使用 default
    @GetMapping("/payment/hystrix/timeout3/{id}")
    public String paymentInfoTimeout3(@PathVariable("id")Integer id) {
        return paymentHystrixService.paymentInfoTimeout3(id);
    }

    /**
     * 超时/异常自定义补救
     * @param id 参数
     * @return 返回值
     */
    public String paymentInfoTimeoutHandler(Integer id){
        return "Consumer_paymentInfo_TimeoutHandler";
    }

    /**
     * 全部fallback方法
     * @return 提示信息
     */
    public String paymentGlobalFallbackMethod(){
        return "Global异常处理信息, 请稍后再试~~~~~~~~";
    }
}
